package com.pinda.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.naming.NoPermissionException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * [Sa-Token 权限认证] 配置类 
 * @author kong
 */
@Configuration
public class SaTokenConfigure {
    // 注册 Sa-Token全局过滤器 
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                // 拦截地址
                .addInclude("/**")    /* 拦截全部path */
                // 开放地址
                .addExclude("/favicon.ico")
                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    // 登录校验 -- 拦截所有路由，并排除/user/doLogin 用于开放登录
                    SaRouter.match("/**", "/authorization/user/doLogin/", r -> StpUtil.checkLogin());
                    // 遍历校验规则，依次鉴权
                    Map<String, String> rules = getAuthRules();
                    for (String path : rules.keySet()) {
                        SaRouter.match(path, () -> StpUtil.checkPermission(rules.get(path)));
                    }
                })
                // 异常处理方法：每次setAuth函数出现异常时进入
                .setError(e -> {
                    if(e instanceof NotLoginException){
                        return new SaResult(11012,"登入超时，请重新登入",null);
                    }else if(e instanceof NotPermissionException){
                        return new SaResult(11051,"您没有权限执行此操作",null);
                    }
                    return  SaResult.error(e.getMessage());
                });

    }
    // 动态获取鉴权规则
    public Map<String, String> getAuthRules() {
        // key 代表要拦截的 path，value 代表需要校验的权限
        Map<String, String> authMap = new LinkedHashMap<>();

        //角色管理 新增 删除 授权 配置
        authMap.put("/auth/pd_auth_role/addRole", "role:add");
        authMap.put("/auth/pd_auth_role/removeRole/**", "role:delete");
        authMap.put("/auth/pd_auth_role/updateRole", "role:update");
        authMap.put("/auth/pd_auth_role/batchAuthorization", "role:auth");
        authMap.put("/auth/pd_auth_role/batchConfig/", "role:config");
        //订单管理
        authMap.put("/aggregation/pd_order/findOrder", "view:list");//订单列表
        authMap.put("/aggregation/pd-task-pickup-dispatch/findPickupOne", "view:show");//订单详情
        authMap.put("oms/pd-order-cargo/findOrderCargoOne", "view:show");//订单详情
        //运单管理
        authMap.put("aggregation/pd-order/findOrderTransport", "view:ydlist");//运单列表
        authMap.put("/oms/pd-order-cargo/findOrderCargoOne", "view:transport");//运单详情
        authMap.put("/aggregation/pd-task-pickup-dispatch/findPickupOne", "view:transport");//运单详情
        authMap.put("/aggregation/pd-task-pickup-dispatch/findPickuppaiOne", "view:transport");//运单详情
        //快递作业管理
        //组织管理 新增 删除 修改
        authMap.put("/auth/pd_core_org/addOrganization", "org:add");
        authMap.put("/auth/pd_core_org/removeOrganization/**", "org:delete");
        authMap.put("/auth/pd_core_org/updateOrganization", "org:update");
        //用户管理 新增 删除 修改
        authMap.put("/auth/pd_auth_user/addUser", "user:add");
        authMap.put("/auth/pd_auth_user/removeUser/**", "user:delete");
        authMap.put("/auth/pd_auth_user/updateUser", "user:update");

        //运输管理 运输任务列表 运输任务列表 司机作业单管理
        authMap.put("/work/pd-task-transport/lcqueryviewresultController", "view:transportTaskManager");
        authMap.put("/work/pd-transport-order/lcquerypagetransportorderview/**", "view:transportTaskManagerDetail");
        authMap.put("/work/pd-driver-job/lcquerydrivertaskcontroller", "view:driverJobManager");

        //订单管理 订单列表 订单详情 订单详情
        authMap.put("/aggregation/pd_order/findOrder", "view:list");
        authMap.put("/aggregation/pd-task-pickup-dispatch/findPickupOne", "view:show");
        authMap.put("oms/pd-order-cargo/findOrderCargoOne", "view:show");
        //运单管理 运单列表 运单详情 运单详情
        authMap.put("aggregation/pd-order/findOrderTransport", "view:ydlist");
        authMap.put("/oms/pd-order-cargo/findOrderCargoOne", "view:transport");
        authMap.put("/aggregation/pd-task-pickup-dispatch/findPickupOne", "view:transport");
        authMap.put("/aggregation/pd-task-pickup-dispatch/findPickuppaiOne", "view:transport");
        authMap.put("/aggregation/pd-task-pickup-dispatch/findPickuppaiOne", "view:transport");
        //快递作业管理 快递作业管理（收） 快递作业管理（派） 快递作业管理（取消） 分配快递员（收） 分配快递员（派） 快递员信息（派） 货品数据
        authMap.put("/aggregation/pd-task-pickup-dispatch/findTickupAndOrder", "view:pickup");
        authMap.put("/aggregation/pd-task-pickup-dispatch/findTickupAndOrderpai", "view:pickup");
        authMap.put("/aggregation/pd-task-pickup-dispatch/findTickupAndOrderquxiao", "view:pickup");
        authMap.put(" /work/pd-task-pickup-dispatch/updatecourierid", "add:taskManager");
        authMap.put(" /work/pd-task-pickup-dispatch/updatecourieridone", "add:taskManager");
        authMap.put(" /aggregation/pd-auth-user/findAuthUserAndCoreOrg", "view:courierList");
        authMap.put(" /base/pd-goods-type/findTruckAndGoods", "view:goodsTypeList");
        // 更多规则 ...
        return authMap;
    }
}
